/**
 * 
 */
package com.m7012e.a_remote.android_remote.network.protocol.echoProtocol;

import java.io.IOException;

import com.leoj.utils.Handler;
import com.leoj.utils.tcp_network.ApplicationProtocol;
import com.leoj.utils.tcp_network.TcpConnection;
import com.m7012e.a_remote.android_remote.network.protocol.echoProtocol.internEvents.BusyDaemonFoundEvent;
import com.m7012e.a_remote.android_remote.network.protocol.echoProtocol.internEvents.DaemonFoundEvent;
import com.m7012e.a_remote.android_remote.network.protocol.echoProtocol.internEvents.FreeDaemonFoundEvent;
import com.m7012e.a_remote.ar_listeners.exception.WrongMessageProtocolException;
import com.m7012e.a_remote.communication.tcpMessages.EvaluatedDistanceMessage;
import com.m7012e.a_remote.communication.tcpMessages.NotAvailableMessage;

/**
 * @author leoj
 *
 */
public class DaemonListingProtocol implements ApplicationProtocol {
	public Handler<DaemonFoundEvent> _listener;

	
	/**
	 * 
	 */
	public DaemonListingProtocol(Handler<DaemonFoundEvent> listener) {
		_listener = listener;
	}
	/* (non-Javadoc)
	 * @see com.leoj.utils.tcp_network.ApplicationProtocol#handleClient(com.leoj.utils.tcp_network.TcpConnection)
	 */
	@Override
	public void handleClient(TcpConnection client) {
		// read the message : only one message to read -> EvaluatedDistance or notavailable
		try {
			Object o = client.read();
			if(o instanceof EvaluatedDistanceMessage){
				EvaluatedDistanceMessage freeMsg = (EvaluatedDistanceMessage) o;
				_listener.handle(new FreeDaemonFoundEvent(freeMsg.distance, freeMsg.address, freeMsg.port));
			}else if(o instanceof NotAvailableMessage){
				NotAvailableMessage busyMsg = (NotAvailableMessage) o;
				_listener.handle(new BusyDaemonFoundEvent(busyMsg.distance));
			}else{
				throw new WrongMessageProtocolException();
			}
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}
